/**
 * 
 */
package com.myBase.core.facade.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.myBase.core.base.entity.PageVo;
import com.myBase.core.common.util.EBeiConstantEnum;
import com.myBase.core.dao.GoldcoinAccountDetailDao;
import com.myBase.core.dao.GoldcoinDao;
import com.myBase.core.dao.GoldcoinOrderDao;
import com.myBase.core.dao.GoldcoinTradeRecordDao;
import com.myBase.core.entity.Goldcoin;
import com.myBase.core.entity.GoldcoinAccountDetail;
import com.myBase.core.entity.GoldcoinOrder;
import com.myBase.core.entity.GoldcoinTradeRecord;
import com.myBase.core.exception.PlatformException;
import com.myBase.core.facade.service.GoldcoinAccountDetailServiceFacade;
import com.myBase.common.persistence.Page;
import com.myBase.common.service.CrudAbstractService;

/**
 * 金币账户子表-记录用户某批次金币使用概况Service
 * @author WuJie
 * @version 2017-05-04
 */
@Service("goldcoinAccountDetailServiceFacade")
public class GoldcoinAccountDetailServiceFacadeImpl extends CrudAbstractService<GoldcoinAccountDetailDao, GoldcoinAccountDetail>
        implements GoldcoinAccountDetailServiceFacade {
    @Autowired
    private GoldcoinAccountDetailDao goldcoinAccountDetailDao;

    @Autowired
    private GoldcoinTradeRecordDao goldcoinTradeRecordDao;

    @Autowired
    private GoldcoinDao goldcoinDao;

    @Autowired
    private GoldcoinOrderDao goldcoinOrderDao;

    public GoldcoinAccountDetail get(String id) {
        return super.get(id);
    }

    public List<GoldcoinAccountDetail> findList(GoldcoinAccountDetail goldcoinAccountDetail) {
        return super.findList(goldcoinAccountDetail);
    }

    public Page<GoldcoinAccountDetail> findPage(Page<GoldcoinAccountDetail> page,
            GoldcoinAccountDetail goldcoinAccountDetail) {
        return super.findPage(page, goldcoinAccountDetail);
    }

    @Transactional(readOnly = false)
    public void save(GoldcoinAccountDetail goldcoinAccountDetail) {
        super.save(goldcoinAccountDetail);
    }

    @Transactional(readOnly = false)
    public void delete(GoldcoinAccountDetail goldcoinAccountDetail) {
        super.delete(goldcoinAccountDetail);
    }

    public Integer getSumGoldCoinByUserAndGoldCoinId(String accountId, String goldCoinPoolId) {
        return goldcoinAccountDetailDao.getSumGoldCoinByUserAndGoldCoinId(accountId, goldCoinPoolId);
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public void saveNewGoldCoinGrant(GoldcoinOrder goldcoinOrder, GoldcoinTradeRecord goldcoinTradeRecord,
            GoldcoinAccountDetail goldcoinAccountDetail, Goldcoin goldcoin) throws PlatformException {

        //修改goldcoin表
//        goldcoin.preUpdate();
        int goldcoinNum = goldcoinDao.updateBySelf(goldcoin);//更新条数不等于1，throw exception，++更新
        if (goldcoinNum != 1) {
            throw new PlatformException("更新goldcoin失败," + goldcoin.toString());
        }
        //保存账户子表
        //        int goldcoinAccountDetailNum = goldcoinAccountDetailDao.saveGoldcoinAccountDetailBySelf(goldcoinAccountDetail,
        //                goldcoin.getGoldcoinlimitnumber());
        super.update(goldcoinAccountDetail);//插入时判断-用户获取的总数总数不能超过限额
        /* if (goldcoinAccountDetailNum != 1) {
            throw new Exception("goldcoinAccountDetail数据更新失败");
        }*/

        //保存订单
//        goldcoinOrder.preInsert();
        int goldcoinOrderNum = goldcoinOrderDao.insert(goldcoinOrder);
        if (goldcoinOrderNum != 1) {
            throw new PlatformException("新增goldcoinOrder失败");
        }
        //保存流水
        goldcoinTradeRecord.setDetailid(goldcoinAccountDetail.getDetailid());
//        goldcoinTradeRecord.preInsert();
        int goldcoinTradeRecordNum = goldcoinTradeRecordDao.insert(goldcoinTradeRecord);
        if (goldcoinTradeRecordNum != 1) {
            throw new PlatformException("新增goldcoinTradeRecord失败");
        }

    }

    public Integer getSumAvailableGoldCoinByAccountId(String accountId) {
        return goldcoinAccountDetailDao.getSumAvailableGoldCoinByAccountId(accountId);
    }

    public ArrayList<GoldcoinAccountDetail> getParamsAvailableGoldCoinByAccountId(String accountId) {
        return goldcoinAccountDetailDao.getParamsAvailableGoldCoinByAccountId(accountId);
    }

    @Transactional(readOnly = false)
    public boolean updateGoldCoinDetailsByUseCoin(Integer useCoin, ArrayList<GoldcoinAccountDetail> list,
            Integer sumAvailableCoin, GoldcoinOrder goldcoinOrder, GoldcoinTradeRecord goldCoinTradeRecord)
                    throws PlatformException {
        //使用的逻辑是，需要使用的金笔数逐步减少，直到为0为止，一个一个的list的取数，减数

        //使用前 sumAvailableCoin
        Integer before = sumAvailableCoin;
        Integer after = 0;
        //申请使用 useCoin
        //使用后 
        for (int i = 0; useCoin > 0; i++) {
            GoldcoinAccountDetail goldcoinAccountDetail = list.get(i);

            //循环批次可用金币数
            Integer noUse = Integer.valueOf(goldcoinAccountDetail.getNouse());
            goldCoinTradeRecord.setBeforeuse(before + "");//金币使用前

            //如果需要金币数大于等于循环批次金币数
            if (useCoin >= noUse) {
                before = before - noUse;//可用金币总数减少
                useCoin = useCoin - noUse;
                goldcoinAccountDetail.setUseall((Integer.valueOf(goldcoinAccountDetail.getUseall()) + noUse) + "");
                goldcoinAccountDetail.setNouse("0");

            } else {
                before = before - useCoin;//可用金币总数减少
                useCoin = 0;
                goldcoinAccountDetail.setUseall((Integer.valueOf(goldcoinAccountDetail.getUseall()) + useCoin) + "");
                goldcoinAccountDetail.setNouse((Integer.valueOf(goldcoinAccountDetail.getNouse()) - useCoin) + "");
            }
//            goldcoinAccountDetail.preUpdate();
            int goldcoinAccountDetailNum = goldcoinAccountDetailDao
                    .updateGoldcoinAccountDetailbyDetailId(goldcoinAccountDetail);
            if (goldcoinAccountDetailNum != 1) {
                throw new PlatformException("更新goldcoinAccountDetail失败");
            }

            goldCoinTradeRecord.setAfteruse(before + "");//金币使用后
            //保存流水
            int goldCoinTradeRecordNum = goldcoinTradeRecordDao.insert(goldCoinTradeRecord);
            if (goldCoinTradeRecordNum != 1) {
                throw new PlatformException("新增goldCoinTradeRecord失败");
            }

        }

        //到这里是成功了
        //保存订单
        //订单状态-成功
        goldcoinOrder.setOrderStatus(EBeiConstantEnum.GOLDCOIN_ORDER_STATUS_SUCCESS.toString());//使用成功
        //订单-保存
        int goldcoinOrderNum = goldcoinOrderDao.insert(goldcoinOrder);
        if (goldcoinOrderNum != 1) {
            throw new PlatformException("新增goldcoinOrder失败");
        }
        return true;
    }

    /**
     *getGoldTOBeFailureList(查询即将过期金币流水) 
     */
    @Transactional(readOnly = false)
    public PageVo<HashMap<String, Object>> getGoldTOBeFailureList(PageVo<HashMap<String, Object>> page,
            GoldcoinAccountDetail goldAccountDetail) throws Exception {
        logger.info("查询即将过期金币流水 service 开始");
        int currentPage = page.getCurrentPage() - 1;
        int pageSize = page.getPageSize();
        int offset = currentPage * page.getPageSize();

        goldAccountDetail.setOffset(offset);//封装起始索引
        goldAccountDetail.setPageSize(pageSize);//封装每页显示条数

        //查询即将过期金币流水 总数
        int goldCount = goldcoinAccountDetailDao.getGoldTOBeFailureCount(goldAccountDetail);
        page.setRecordCount(goldCount);
        logger.info("查询即将过期金币流水总数为" + goldCount);
        List<HashMap<String, Object>> golds = goldcoinAccountDetailDao.getGoldTOBeFailureList(goldAccountDetail);
        page.setVoList(golds);
        logger.info("查询即将过期金币流水 service 开始");
        return page;
    }

    /**
     *getUserGoldSum(查询用户金币总数 和 即将过期数量) 
     */
    @Transactional(readOnly = false)
    public HashMap<String, Object> getUserGoldSum(GoldcoinAccountDetail goldAccountDetail) throws Exception {
        logger.info("查询用户金币总数 和 即将过期数量 service 开始");
        HashMap<String, Object> map = new HashMap<String, Object>();
        int userGoldSum = goldcoinAccountDetailDao.getUserGoldSum(goldAccountDetail);
        int goldTOBeFailureSum = goldcoinAccountDetailDao.getUserGoldTOBeFailureSum(goldAccountDetail);
        logger.info("查询用户金币总数=" + userGoldSum + ",即将过期数量=" + goldTOBeFailureSum);
        map.put("totalGold", userGoldSum);
        map.put("toBeFailure", goldTOBeFailureSum);
        logger.info("查询用户金币总数 和 即将过期数量 service 结束");
        return map;
    }

    /**
     * EBeiGoldCoinAccountDetailOverdueTrigger(goldcoinaccount_detail搜索endtime小于等于现在但是金币状体正常的数据) 
     */
    public ArrayList<GoldcoinAccountDetail> getOverdueBeanListGoldCoinAccountDetail() {
        return goldcoinAccountDetailDao.getOverdueBeanListGoldCoinAccountDetail();
    }

    /**
     * 更新为过期
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public void updateDetailSaveRradeRecord(GoldcoinTradeRecord goldcoinTradeRecord,
            GoldcoinAccountDetail goldcoinAccountDetail) throws PlatformException {
        //更新goldcoinaccountdetail
//        goldcoinAccountDetail.preUpdate();
        int goldcoinAccountDetailNum = goldcoinAccountDetailDao.updateGoldcoinAccountDetailbyDetailIdForStatus(
                goldcoinAccountDetail, EBeiConstantEnum.GOLDCOIN_ACCOUNTDETAIL_STATUS_NORMAL.toString());
        if (goldcoinAccountDetailNum != 1) {
            throw new PlatformException("更新goldcoinAccountDetail异常");
        }

        if (!"0".equals(goldcoinTradeRecord.getBeforeuse())) {
            //保存 流水 goldcoinRradeRecord
//            goldcoinTradeRecord.preInsert();//新增
            int goldcoinTradeRecordNum = goldcoinTradeRecordDao.insert(goldcoinTradeRecord);
            if (goldcoinTradeRecordNum != 1) {
                throw new PlatformException("新增goldcoinTradeRecord异常");
            }
            logger.info("用户领取的该批次金币过期，过期的金币数为：" + goldcoinTradeRecord.getBeforeuse() + ",增加流水记录");
        } else {
            logger.info("用户领取的该批次金币过期，但是过期金币数为0，仅修改该批次领取金币状态为过期，不增加流水记录");
        }

    }

}